package com.dylan.历史.多线程.并发编程的艺术.原子操作;

import com.dylan.历史.util.LogUtil;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;

/**
 * Created by Dylan on 2018/9/20.
 */
public class 引用类型及数组 {

    public static void main(String[] args) {
        User user1 = new User("ankang", 1);
        AtomicReference<User> userRef = new AtomicReference<>(user1);
        User user2 = new User("xinze", 2);

        // 原子方式更新对象
        userRef.compareAndSet(user1, user2);
        LogUtil.info(userRef.get());

        // 原子方式更新对象数组
        AtomicReferenceArray<User> userRefArray = new AtomicReferenceArray<User>(new User[]{user1, user2});
        userRefArray.compareAndSet(1, user2, new User("dylan", 3));
        LogUtil.info(userRefArray.get(1));
    }

    static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
